package org.jackysoft.security;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.entity.User;
import org.jackysoft.entity.nosql.OperationLog;
import org.jackysoft.service.OperationLogService;
import org.jackysoft.service.UserService;
import org.jackysoft.util.OperationType;
import org.springframework.dao.DataAccessException;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component("userDetailsService")
public class HibernateUserDetailService implements UserDetailsService,
		AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {
	private final static Log log = LogFactory.getLog(HibernateUserDetailService.class);
    private OperationLogService logService;
	private UserService userService;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		assert username != null : "username can not be empty or null ";		
		User user = userService.getByLogin(username);		
		if (user == null) {
			throw new UsernameNotFoundException("User named by "+username+" not found");
		}      
		String userName = user.getUsername();
		OperationLog oprLog = new OperationLog();
		oprLog.setCreateDate(new Date());
		oprLog.setDetails("User "+user.getUsername()+" "+user.getLocalName()+" signed in" );
		oprLog.setOprType(OperationType.System);
		oprLog.setName("登录");
		logService.create(oprLog);
		log.info("User " + userName+"|"+ user.getLocalName()+" signed  ");
		return user;

	}

	@Override
	public UserDetails loadUserDetails(CasAssertionAuthenticationToken token)
			throws UsernameNotFoundException {
		log.info("User " + token.getName()+" has logined ");
		return loadUserByUsername(token.getName());
	}

	@Resource
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Resource
	public void setLogService(OperationLogService logService) {
		this.logService = logService;
	}

	

}
